import {Utils} from "jboot-env";

const defaultCheckPwdOptions = {
	min: 8,
	max: 16
};

function checkPwdSecurity (pwd, options){
	const validResult = {
		message: '',
		level: -1
	};

	try {
		Utils.isNotEmpty(pwd, '密码不能为空');

		const {min, max} = {...defaultCheckPwdOptions, ...options};

		Utils.assert(pwd.length >= min, `密码长度少于${min}位`);
		Utils.assert(pwd.length <= max, `密码长度大于${max}位`);

		const numReg = /\d+/;
		const zmUp = /[A-Z]+/;
		const zmLow = /[a-z]+/;
		const symbolReg = /[`~!@#$%^&*(_\-=?:,.;]+/;

		validResult.level = [numReg, zmUp, zmLow, symbolReg].map(reg => reg.test(pwd)).filter(Boolean).length;
	} catch (e){
		validResult.message = e.message.replace('[jboot]', '');
	}

	return validResult;
}

export default {
	/**
	 * 校验密码强度
	 * @param rule
	 * @param value
	 * @param callback
	 */
	handleValidatorPwd (rule, value, callback){
		const {message, level} = checkPwdSecurity(value);

		switch (level){
			case 1:
			case 2:
			case 3:
				callback('密码须由大写字母、小写字母、数字、特殊符号组成');
				break;
			case 4:
				if(/[<>')+\/]+/.test(value)){
					callback('密码中不允许包含<>\')+/');
				}else{
					callback();
				}

				break;
			default:
				callback(message || '密码不符合要求');
		}
	},

	/**
	 * 获取某个类型的附件
	 * @param sysAttachments 附件集合
	 * @param type 附件类型
	 * @return {function(*=): *[]}
	 */
	getAttachmentByType (sysAttachments, type){
		return Utils.blank2Default(sysAttachments, []).filter(item => item.bizFieldName === type) ?? [];
	},

	/**
	 * 设置附件为某个类型
	 * @param sysAttachments 附件集合
	 * @param type 附件类型
	 * @return *[]
	 */
	setAttachmentType (sysAttachments, type){
		return Utils.blank2Default(sysAttachments, []).map(item => {
			return {
				...item,
				bizFieldName: type
			}
		});
	},
}
